
<style scoped>
.newslist{
    /*background-color: #1890ff;*/
    padding: 10px;
    margin-bottom: 50px;
    width: 75%;
}
.newsli{
    padding-bottom: 6px;
    border-bottom: 1px solid #d1a9a9;
    margin-bottom: 9px;
    cursor: pointer;
}
.news_title{
  margin: 0 0 0 17px;
  width: 700px;
}
.news_time{
    font-size: 13px;
    color: #939393;
    line-height: 26px;
    position: absolute;
    right: 16px;
}
.newsTop{
    display: flex;
    position: relative;
    margin-bottom: 11px;
}
.badge {
  display: inline-block;
  color: white;
  padding: 5px 9px;
  width: 25px;
  border-radius: 8px;
  font-size: 11px;
  text-align: center;
  box-shadow: 0 2px 5px rgb(0 0 0 / 20%);
  height: 16px;
}
.news_content{
  margin-bottom: 9px;
  width: 755px;
  padding-right: 28px;
  font-size: 20px;
  padding-top: 4px;
}
.news_img{
  width: 245px;
  margin-right: 20px;
  height: 156px;
}
.relatedStockArea{
  display: flex;
  width: 866px;
}
.relatedStock{
  margin-left: 6px;
  font-size: 12px;
  color: #686868;
  margin-top: 5px;
}
.news_content_area{
  display: flex;
}
.newsType{
  margin-left: 27px;
}
</style>

<template>
    <div class="newslist">
        <div class="newsli" v-for="(item,index) in JournalismLists" :key="index" @click="ToContent(item.id)">
            <div class="newsTop">
                <div
                    class="badge"
                    :style="{backgroundColor:item.sentiment==='利好'?'red':'#008000c7'}"
                >{{item.sentiment}}</div>
                <div>
                  <h3
                      class="news_title"
                      :style="{'color':getHasCheckedJournalism(item.id)?'#969696':'black'}"
                  >{{item.title}}</h3>
                  <div class="relatedStockArea">
                    <div class="relatedStock">#{{item.stockCode+' '+item.stockName}}</div>
                    <div class="relatedStock newsType">{{item.newsType}}</div>
                  </div>
                </div>
                <div class="news_time">{{item.originName+' '+item.publishDate}}</div>
            </div>
            <div class="news_content_area">
              <div class="news_content" :style="{'color':getHasCheckedJournalism(item.id)?'#555454':'black'}">{{item.content}}</div>
              <div v-if="item.imageSrc!==null">
                <img class="news_img" :src="item.imageSrc" alt="">
              </div>
              <div v-if="item.imageSrc===null" style="width: 245px;height: 156px;"></div>
            </div>
        </div>
      <div style="margin-top: 20px">
        <el-pagination
            @change="ToThisPage"
            style="display: flex;justify-content: center;"
            :page-size="8"
            :pager-count="11"
            background
            v-model:current-page="currentPage"
            layout="prev, pager, next"
            :total="AllNewsNumber" />
      </div>
    </div>
</template>

<script setup>
import {ref, watch, toRaw, onUnmounted} from "vue";
    import {useRouter} from "vue-router";
    import {useCounterStore} from "@/stores/counter.js";
    import { updateJournalismList} from "@/api/request.js";

    let Router=useRouter()
    let store=useCounterStore()

// 判断是否已经点开过这条新闻，点开过的新闻标题会变灰
    function getHasCheckedJournalism(id) {
      let data=JSON.parse(localStorage.getItem('hasCheckedJournalism')) || [];
      return data.indexOf(id.toString()) !== -1;
    }

let JournalismLists=ref([])

    let currentPage=ref(store.findSuitableJournalisms.pageNo===null?1:store.findSuitableJournalisms.pageNo)
    let AllNewsNumber=ref(null)

    let requestQuery=null
    watch(()=>store.findSuitableJournalisms,() => {
      if(store.OnlyVisitToday){
        return
      }
      requestQuery=store.findSuitableJournalisms
      getJourLists()
    },{deep:true,immediate:true})

    watch(()=>store.OnlyVisitToday,()=>{
      if(store.OnlyVisitToday){
        const today = new Date();
        requestQuery=store.findSuitableJournalisms
        requestQuery.startTime=new Date(today.getFullYear(), today.getMonth(), today.getDate(), 0, 0, 0);
        requestQuery.endTime=new Date(today.getFullYear(), today.getMonth(), today.getDate(), 23, 59, 59);
        store.OnlyVisitToday=false
        getJourLists()
      }
    })

// 请求新闻列表数据
    async function getJourLists() {
      requestQuery.pageNo = currentPage.value
      let message=await updateJournalismList(toRaw(requestQuery))
      JournalismLists.value=[]
      AllNewsNumber.value = message.total
      let response = message.records
      for (let i = 0; i < response.length; i++) {
        response[i].imageSrc=await CheckImgValid(response[i].imageSrc)
        switch (response[i].sentiment) {
          case "neutral": response[i].sentiment='中性';
            break;
          case "positive": response[i].sentiment='利好';
            break;
          case "negative": response[i].sentiment='利空';
          break;
        }
        if(response[i].content!==null && response[i].content.length>150){
            response[i].content=response[i].content.slice(0,150)+'...';
        }
      }
      JournalismLists.value = response
    }

    function ToThisPage() {
      store.findSuitableJournalisms.pageNo=currentPage.value
    }

    // 检查图片是否有效，无效则返回null
    async function CheckImgValid(url) {
      if (url === null) {
        return null;
      }
      return new Promise((resolve) => {
        const img = new Image();
        img.src = url;
        // 图像加载成功
        img.onload = () => {
          resolve(url); // 图像有效，返回 URL
        };
        // 图像加载失败
        img.onerror = () => {
          resolve(null); // 图像无效，返回 null
        };
      });
    }

    function ToContent(id) {
      Router.push({
        path:'/journalismContent',
        query:{jourId:id}
      })
    }

</script>